//
// Created by vista on 2017/12/11.
//

#ifndef P_P13_H
#define P_P13_H

#include <vector>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <iostream>
#include <stack>
using namespace std;

class Solution {
public:

/*  cout << solution.intToRoman(1) << endl;
    cout << solution.intToRoman(9) << endl;
    cout << solution.intToRoman(10) << endl;
    cout << solution.intToRoman(99) << endl;
    cout << solution.intToRoman(100) << endl;
    cout << solution.intToRoman(999) << endl;
    cout << solution.intToRoman(3999) << endl;

    cout << solution.romanToInt("I") << endl;
    cout << solution.romanToInt("IX") << endl;
    cout << solution.romanToInt("X") << endl;
    cout << solution.romanToInt("XCIX") << endl;
    cout << solution.romanToInt("C") << endl;
    cout << solution.romanToInt("CMXCIX") << endl;
    cout << solution.romanToInt("MMMCMXCIX") << endl;
    */
    int romanToInt(string s) {
        string romanPieces[] = {"","I","II","III","IV","V","VI","VII","VIII","IX",
                                "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
                                "","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
                                "","M","MM","MMM","MMMM"};
        int len = sizeof(romanPieces)/ sizeof(string);
        int val = 0;
        while (s.length()>0){
            int len0 = std::min((int)s.length(),4);
            do {
                auto ptr = find(romanPieces, romanPieces + len, s.substr(0, static_cast<unsigned long>(len0)));
                auto index0 = static_cast<int>(ptr - romanPieces);
                if(index0 != len){
                    if (index0 > 30){
                        val += (index0 - 30 ) * 1000;
                    }else if(index0 > 20){
                        val += (index0 - 20) * 100;
                    }else if(index0 > 10){
                        val += (index0 - 10) * 10;
                    }else
                        val += index0;

                    s = s.erase(0, static_cast<unsigned long>(len0));
                    break;
                }
                --len0;
            }while (len0 > 0);
        }
        return val;
    }
};

#endif //P_P13_H
